package cn.net.wanji.config.websocket;


import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.service.DataReceiveService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:
 * @Date:
 * @Description: 配置websocket后台客户端
 */
@Slf4j
@Component
public class WebSocketClientConfig {



    @Resource
    private DataReceiveService dataReceiveService;

    @Resource
    private ApplicationConfig applicationConfig;

    private ScheduledExecutorService executorService;


    @Bean
    public WebSocketClient webSocketClient() {
        try {

            WebSocketClient webSocketClient = new WebSocketClient(new URI(applicationConfig.getAiAddress()),new Draft_6455()) {

                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("[websocket] 连接成功");
                }

                @SneakyThrows
                @Override
                public void onMessage(String message) {
//                    log.info("[websocket] 收到消息={}",message);
                    //算法组发送入口和出口区域感知结果

                    dataReceiveService.AIDataToKafka(message);

                }


                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("[websocket] 退出连接");
                    reconnect();
                }


                @Override
                public void onError(Exception ex) {
                    log.info("[websocket] 连接错误={}",ex.getMessage());



                }
            };

            webSocketClient.connect();

            return webSocketClient;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;
    }

    private void reconnect() {
        if (executorService == null || executorService.isShutdown()) {
            executorService = Executors.newSingleThreadScheduledExecutor();
        }
        executorService.schedule(() -> {
            try {
                log.info("[websocket] 重新连接中...");
                WebSocketClient webSocketClient = new WebSocketClient(new URI(applicationConfig.getAiAddress()), new Draft_6455()) {
                    @Override
                    public void onOpen(ServerHandshake handshakedata) {
                        log.info("[websocket] 连接成功");
                    }

                    @SneakyThrows
                    @Override
                    public void onMessage(String message) {
//                        log.info("[websocket] 收到消息={}",message);
                        //算法组发送入口和出口区域感知结果
                        dataReceiveService.AIDataToKafka(message);

                    }
                    @Override
                    public void onClose(int code, String reason, boolean remote) {
                        log.info("[websocket] 退出连接");
                        reconnect();
                    }


                    @Override
                    public void onError(Exception ex) {
                        log.info("[websocket] 连接错误={}",ex.getMessage());

                    }
                    // 重新连接时的各种回调方法，与上面的WebSocketClient相同
                };
                webSocketClient.connect();
            } catch (Exception e) {
                e.printStackTrace();
                reconnect();
            }
        }, 5, TimeUnit.SECONDS); // 5秒后尝试重新连接
    }


}
